# -*- coding:utf8 -*-

import json
from scpy.xawesome_time import now, parse_time
import copy


class TransDictClass(object):
    '''
    #
    '''

    def transDicts(self, arawDict, atemplateDict, atransDict):
        aresultDict = copy.deepcopy(atemplateDict)
        for key in aresultDict:
            '''
            #key : 结果字典resultDict 的key
            #transDict[key]：转换字典的value，也是网站输出的原始字典的key
            #rawDict[transDict[key]]：把网站输出的原始字典的value传给结果字典的value
            '''
            if atransDict[key]:
                try:
                    if atransDict[key] in arawDict:
                        aresultDict[key] = arawDict[atransDict[key]]
                    else:
                        aresultDict[key] = ''
                except:
                    # 若为空,保持结果字典的原始值
                    pass
        return aresultDict

    def formatDicts(self, raw_dict, template_dict, trans_dict):

        aresultDict = {}
        rawDict = raw_dict
        templateDict = template_dict
        transDict = trans_dict

        # 基本信息
        # aresultDict['_id']=''
        aresultDict['province'] = 'cq_bak'
        aresultDict['basicList'] = []

        aresultDict['basicList'].append(
            self.transDicts(rawDict["IcPublic"][0]["base"], templateDict['basicList'][0], transDict['basicList'][0]))
        aresultDict['basicList'][0]['openFrom'] = parse_time(aresultDict['basicList'][0]['openFrom'])
        aresultDict['basicList'][0]['ancheDate'] = parse_time(aresultDict['basicList'][0]['ancheDate'])
        aresultDict['basicList'][0]['esDate'] = parse_time(aresultDict['basicList'][0]['esDate'])
        if 'opscotype' in rawDict["IcPublic"][0]["base"]:
            aresultDict['basicList'][0]['operateScope'] = rawDict["IcPublic"][0]["base"]['opscotype']
        if 'regCapCur' in aresultDict['basicList'][0] and aresultDict['basicList'][0]['regCapCur']:
            pass
        else:
            aresultDict['basicList'][0]['regCapCur'] = '人民币'
        if aresultDict['basicList'][0]['revokeDate']:
            aresultDict['basicList'][0]['revokeDate'] = parse_time(aresultDict['basicList'][0]['revokeDate'])

        # #股份信息
        # i = 0 #"gInvaccon"
        shareHolderList = []
        if rawDict["IcPublic"][0].has_key("investors"):
            for i, alist_dict in enumerate(rawDict["IcPublic"][0]["investors"]):
                aresultDict_shareHolderList_dict = self.transDicts(alist_dict, templateDict['shareHolderList'][0],
                                                                   transDict['shareHolderList'])
                if rawDict["IcPublic"][0]["investors"][i].has_key("gInvaccon"):
                    # for alist_dict in rawDict["IcPublic"][0]["investors"][i]["gInvaccon"]:
                    if rawDict["IcPublic"][0]["investors"][i]["gInvaccon"]:
                        alist_dict = rawDict["IcPublic"][0]["investors"][i]["gInvaccon"][0]
                        aresultDict_shareHolderList_i_ = copy.deepcopy(aresultDict_shareHolderList_dict)
                        aresultDict_shareHolderList_i_["conDate"] = parse_time(alist_dict["accondate"])
                        # aresultDict_shareHolderList_i_["funded"] = alist_dict["acconam"]
                        aresultDict_shareHolderList_i_["regCapCur"] = ''
                        shareHolderList.append(aresultDict_shareHolderList_i_)
                    else:
                        aresultDict_shareHolderList_i_ = copy.deepcopy(aresultDict_shareHolderList_dict)
                        shareHolderList.append(aresultDict_shareHolderList_i_)

        aresultDict['shareHolderList'] = shareHolderList

        # 企业主要管理人员
        members_list = []
        if rawDict["IcPublic"][0].has_key("members"):
            for alist_dict in rawDict["IcPublic"][0]["members"]:
                members_list.append(
                    self.transDicts(alist_dict, templateDict['personList'][0], transDict['personList'][0]))

        aresultDict['personList'] = members_list

        # print json.dumps(aresultDict, ensure_ascii=True, indent=4)

        # 行政处罚(空)
        # if rawDict["IcPublic"][0].has_key("punishments"):
        #     aresultDict['caseInfoList'] = rawDict["IcPublic"][0]["punishments"]
        aresultDict['caseInfoList'] = []
        # 失信被执行人信息(空)
        aresultDict['punishBreakList'] = []

        # 被执行人信息(空)
        # if rawDict["IcPublic"][0].has_key("illegals"):
        #     aresultDict['punishedList'] = rawDict["IcPublic"][0]["illegals"]
        aresultDict['punishedList'] = []
        # 阿里欠贷信息(空)
        aresultDict['alidebtList'] = []
        # print json.dumps(aresultDict, ensure_ascii=True, indent=4)

        # 对外投资信息
        # aresultDict['entinvItemList'] = rawDict["IcPublic"][0]["dwdbinfo"]

        # 企业对外投资信息
        aresultDict['entinvItemList'] = []

        # aresultDict['entinvItemList'].append({
        #             "entName": "",  # 企业 (机构 )名称
        #             "entType": "",  # 企业 (机构 )类型
        #             "fundedRatio": "",  # 出资比例
        #             "currency": "",   # 认缴出资币种
        #             "entStatus": "",  # 企业状态
        #             "canDate": "",    # 注销日期
        #             "esDate": "",     # 开业日期
        #             "regOrg": "",     # 登记机关
        #             "regCapcur": "",  # 注册资本币种
        #             "regCap": "",     # 注册资本(万元 )
        #             "revDate": "",    # 吊销日期
        #             "name": "",       # 法定代表人姓名
        #             "subConam": "",   # 认缴出资额 (万元)
        #             "regNo": ""       # 注册号
        #         })



        aresultDict['frinvList'] = []  # 法定代表人对外投资信息(空)
        aresultDict['frPositionList'] = []  # 法定代表人在其他企业任职信息(空)

        # 分支机构信息(空)
        # if rawDict["IcPublic"][0].has_key("brunchs"):
        #     aresultDict['filiationList'] = rawDict["IcPublic"][0]["brunchs"]
        aresultDict['filiationList'] = []
        aresultDict['sharesFrostList'] = []  # 股权冻结历史信息(空)

        aresultDict['sharesImpawnList'] = []  # 股权出质历史信息(空)

        aresultDict['morDetailList'] = []  # 动产质押信息(空)
        # 动产抵押物信息(空)
        # if rawDict["IcPublic"][0].has_key("motage"):
        #     aresultDict['morguaInfoList'] = rawDict["IcPublic"][0]["motage"]
        aresultDict['morguaInfoList'] = []

        # 清算信息(空)
        # if rawDict["IcPublic"][0].has_key("accounts"):
        #     aresultDict['liquidationList'] = rawDict["IcPublic"][0]["accounts"]
        aresultDict['liquidationList'] = []
        # 企业历史变更信息
        alters_list = []
        if rawDict["IcPublic"][0].has_key("alters"):
            for alist_dict in rawDict["IcPublic"][0]["alters"]:
                alters_list.append(self.transDicts(alist_dict, templateDict['alterList'][0], transDict['alterList'][0]))
            for a in alters_list:
                a['altDate'] = parse_time(a['altDate'])

        aresultDict['alterList'] = alters_list

        # 抽查检查信息
        checkMessage_list = []
        if rawDict["IcPublic"][0].has_key('ccjc'):
            for i, alist_dict in enumerate(rawDict["IcPublic"][0]['ccjc']):
                checkMessage_list.append(
                    self.transDicts(alist_dict, templateDict['checkMessage'][0], transDict['checkMessage'][0]))
                for a_checkMessage in checkMessage_list:
                    checkMessage_list[i]['check_date'] = parse_time(a_checkMessage['check_date'])
                    checkMessage_list[i]['seq_no'] = str(i + 1)

        aresultDict['checkMessage'] = checkMessage_list

        # 经营异常信息
        aresultDict['abnormalOperation'] = []
        if rawDict["IcPublic"][0].has_key('qyjy'):
            aresultDict['abnormalOperation'] = rawDict["IcPublic"][0]['qyjy']
            for a in aresultDict['abnormalOperation']:
                a['abntime'] = parse_time(a['abntime'])

        # 股权出质登记信息
        # if rawDict["IcPublic"][0].has_key("stock"):
        #     aresultDict['sharesImpawnList'] = rawDict["IcPublic"][0]["stock"]
        #     for a in aresultDict['sharesImpawnList']:
        #         a['equpledate'] = parse_time(a['equpledate'])
        # else:
        #     aresultDict['sharesImpawnList'] = []

        # 企业年报部分
        # 企业基本信息
        yearReport_list = []
        # i_year = 0
        for i_year, aYearItem in enumerate(rawDict["allAnnualReports"]):
            ayearReportList_dict = {}
            ayearReportList_dict["year"] = rawDict["allAnnualReports"][i_year].get("year", "")
            if rawDict["allAnnualReports"][i_year].has_key("base"):
                alist_dict = rawDict["allAnnualReports"][i_year]["base"]

                if 'haswebsite' in alist_dict:
                    if alist_dict['haswebsite'] == '1' or alist_dict['haswebsite'] == '是':
                        alist_dict['haswebsite'] = '是'
                    else:
                        alist_dict['haswebsite'] = '否'

                if 'istransfer' in alist_dict:
                    if alist_dict['istransfer'] == '1' or alist_dict['istransfer'] == '是':
                        alist_dict['istransfer'] = '是'
                    else:
                        alist_dict['istransfer'] = '否'

                if 'empnum' not in alist_dict:
                    alist_dict['empnum'] = '企业选择不公示'

                if 'hasbrothers' in alist_dict:
                    if alist_dict['hasbrothers'] == '0' or alist_dict['hasbrothers'] == '否':
                        alist_dict['hasbrothers'] = '否'
                    else:
                        alist_dict['hasbrothers'] = '有'

                if 'opstate' in alist_dict:
                    if alist_dict['opstate'] == '1' or alist_dict['opstate'] == '开业':
                        alist_dict['opstate'] = '开业'
                    elif alist_dict['opstate'] == '2' or alist_dict['opstate'] == '歇业':
                        alist_dict['opstate'] = '歇业'
                    elif alist_dict['opstate'] == '3' or alist_dict['opstate'] == '清算':
                        alist_dict['opstate'] = '清算'

                ayearReportList_dict['baseInfo'] = self.transDicts(alist_dict,
                                                                   templateDict['yearReportList'][0]['baseInfo'],
                                                                   transDict['yearReportList'][0]['baseInfo'])

            # 网站或网店信息
            if rawDict["allAnnualReports"][i_year].has_key("webSites"):
                webSites_list = rawDict["allAnnualReports"][i_year]["webSites"]
                if webSites_list:
                    alist_dict = webSites_list[0]
                    ayearReportList_dict['website'] = self.transDicts(alist_dict,
                                                                      templateDict['yearReportList'][0]['website'],
                                                                      transDict['yearReportList'][0]['website'])
            else:
                ayearReportList_dict['website'] = {}

            # 发起人及出资信息
            investorInformations_list = []
            if rawDict["allAnnualReports"][i_year].has_key("mNGsentinv"):
                for alist_dict in rawDict["allAnnualReports"][i_year]["mNGsentinv"]:
                    # import pdb
                    # pdb.set_trace()
                    # import json
                    # json.dumps(alist_dict, indent=4,ensure_ascii=False)
                    # investorInformations_dict_ = self.transDicts(alist_dict, templateDict['yearReportList'][0]['investorInformations'][0], transDict['yearReportList'][0]['investorInformations'][0])
                    investorInformations_dict = {}
                    investorInformations_dict['shareholderName'] = alist_dict["inv"]
                    # 认缴
                    if "conform" in alist_dict["mNGsentinvsubcon"]:
                        investorInformations_dict["subConType"] = alist_dict["mNGsentinvsubcon"]["conform"]
                    else:
                        investorInformations_dict["subConType"] = ''

                    if "subconam" in alist_dict["mNGsentinvsubcon"]:
                        investorInformations_dict["subConam"] = alist_dict["mNGsentinvsubcon"]["subconam"]
                    else:
                        investorInformations_dict["subConam"] = ''

                    if "condate" in alist_dict["mNGsentinvsubcon"]:
                        investorInformations_dict["subConDate"] = parse_time(alist_dict["mNGsentinvsubcon"]["condate"])
                    else:
                        investorInformations_dict["subConDate"] = ''

                    # 实缴
                    if alist_dict["mNGsentinvaccon"].has_key("acconform"):
                        investorInformations_dict["paidType"] = alist_dict["mNGsentinvaccon"]["acconform"]
                    else:
                        investorInformations_dict["paidType"] = ''

                    if alist_dict["mNGsentinvaccon"].has_key("acconam"):
                        investorInformations_dict["paidConMoney"] = alist_dict["mNGsentinvaccon"]["acconam"]
                    else:
                        investorInformations_dict["paidConMoney"] = ''

                    if alist_dict["mNGsentinvaccon"].has_key("accondate"):
                        investorInformations_dict["paidTime"] = parse_time(alist_dict["mNGsentinvaccon"]["accondate"])
                    else:
                        investorInformations_dict["paidTime"] = ''

                    # investorInformations_dict["mNGsentinvsubcon"] = self.transDicts(alist_dict['mNGsentinvsubcon'], templateDict['yearReportList'][0]['investorInformations'][0]['mNGsentinvsubcon'], transDict['yearReportList'][0]['investorInformations'][0]['mNGsentinvsubcon'])
                    #
                    # # 时间转化
                    # investorInformations_dict["mNGsentinvsubcon"]['subConDate'] = parse_time(investorInformations_dict["mNGsentinvsubcon"]['subConDate'])
                    #
                    # investorInformations_dict["mNGsentinvaccon"] = self.transDicts(alist_dict['mNGsentinvaccon'], templateDict['yearReportList'][0]['investorInformations'][0]['mNGsentinvaccon'], transDict['yearReportList'][0]['investorInformations'][0]['mNGsentinvaccon'])
                    # investorInformations_dict["mNGsentinvaccon"]['paidTime'] = parse_time(investorInformations_dict["mNGsentinvaccon"]['paidTime'])
                    #
                    investorInformations_list.append(investorInformations_dict)

            ayearReportList_dict['investorInformations'] = investorInformations_list

            # 企业资产状况信息
            if rawDict["allAnnualReports"][i_year].has_key("means"):
                ayearReportList_dict['assetsInfo'] = self.transDicts(rawDict["allAnnualReports"][i_year]["means"],
                                                                     templateDict['yearReportList'][0]['assetsInfo'],
                                                                     transDict['yearReportList'][0]['assetsInfo'])
            else:
                ayearReportList_dict['assetsInfo'] = {}

            # 股权变更信息
            equityChangeInformations_list = []
            if rawDict["allAnnualReports"][i_year].has_key("stocks"):
                for alist_dict in rawDict["allAnnualReports"][i_year]["stocks"]:
                    equityChangeInformations_list.append(
                        self.transDicts(alist_dict, templateDict['yearReportList'][0]['equityChangeInformations'][0],
                                        transDict['yearReportList'][0]['equityChangeInformations'][0]))

                for a in equityChangeInformations_list:
                    a['time'] = parse_time(a['time'])

            ayearReportList_dict['equityChangeInformations'] = equityChangeInformations_list


            # 修改记录
            changeRecords_list = []
            if rawDict["allAnnualReports"][i_year].has_key("modifies"):
                for alist_dict in rawDict["allAnnualReports"][i_year]["modifies"]:
                    changeRecords_list.append(
                        self.transDicts(alist_dict, templateDict['yearReportList'][0]['changeRecords'][0],
                                        transDict['yearReportList'][0]['changeRecords'][0]))
                for a in changeRecords_list:
                    a['time'] = parse_time(a['time'])
            ayearReportList_dict['changeRecords'] = changeRecords_list

            yearReport_list.append(ayearReportList_dict)

        aresultDict['yearReportList'] = yearReport_list

        return aresultDict


if __name__ == "__main__":
    pass
